import storeUtil from "@pangza-club/utils/store";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

interface IProps {
    children: any;
    auth?: boolean;
    role?: string[];
}

function hasPermission(permission: string | string[]) {
    const user = storeUtil.get<LoginVO>('user');
    if (!user) return false;
    if (!user.roles) return false;
    if (!permission) return true;
    let innerPermission: string[] = [];

    if (!Array.isArray(permission)) {
        innerPermission = permission.split(',');
    } else {
        innerPermission = permission;
    }

    const result: boolean[] = [];

    innerPermission.forEach(_permission => {
        result.push(user.roles!.includes(_permission));
    });

    return result.some(item => item);
}


const RouteBeforeEach = (props: IProps) => {

    const user = storeUtil.get('user');

    const nav = useNavigate();

    useEffect(() => {
        if(props.auth) {
            if(!user || !user.token) {
                nav('/login');
            } else {
                if(props.role) {
                    const flag = hasPermission(props.role);
                    if(!flag) {
                        nav('/403');
                    }
                }
            }
        }
    }, []);

    return <div>
        {props.children}
    </div>
}

export default RouteBeforeEach;